/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.thinkcube.edutainment.login;

import java.io.IOException;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.LoginActivity_;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.User;
import com.thinkcube.edutainment.service.SPreferences_;

@EActivity
@SuppressLint("SetJavaScriptEnabled")
public class WebViewActivity extends Activity {
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		webView.clearCache(true);
		webView.destroy();
	}

	// TODO: Rename and change types and number of parameters
	public static Class<WebViewActivity_> newInstance() {
		// WebViewActivity fragment = new WebViewActivity_();

		return WebViewActivity_.class;
	}

	private WebView webView;

	public class WebAppInterface {
		Context mContext;

		/** Instantiate the interface and set the context */
		WebAppInterface(Context c) {
			mContext = c;
		}

		/** Show a toast from the web page */
		@JavascriptInterface
		public void showToast(String toast) {

			createUser(toast);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.web_view);

		webView = (WebView) findViewById(R.id.webView);
		webView.setWebViewClient(new MyWebViewClient());

		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

		webView.loadUrl(EdutainmentConstant.DIALOG_OAUTH_CALLBACK_URL);

		webView.addJavascriptInterface(new WebAppInterface(this), "Android");
		webView.setWebViewClient(new MyWebViewClient());

		webView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				Log.d("d3", message);
				result.confirm();
				return true;
			}

			@Override
			public void onProgressChanged(final WebView view, final int progress) {
				WebViewActivity.this.setTitle("Loading...");
				WebViewActivity.this.setProgress(progress * 100);

				if (progress == 100) {
					WebViewActivity.this.setTitle(R.string.app_name);
				}
			}
		});
	}

	@RestService
	UserClient userClient;

	@Trace
	@Background
	void doBackground(String param) {
		// MultiValueMap<String, String> mvMap = new LinkedMultiValueMap<String,
		// String>();
		// mvMap.add("data", param);
		// System.out.println("param" + param);

		new ReachabilityTest(getApplicationContext(),
				new ReachabilityTest.Callback() {

					@Override
					public void onReachabilityTestPassed() {

						try {
							doUi(userClient.getSystemUser());
						} catch (Exception e) {
							e.printStackTrace();

						}
					}

					@Override
					public void onReachabilityTestFailed() {
						System.out.println("cec");
					}
				});
	}

	@Background
	void createUser(final String param) {
		final MultiValueMap<String, String> mvMap = new LinkedMultiValueMap<String, String>();
		mvMap.add("loginResponse", param);
		System.out.println("loginResponse" + param);

		new ReachabilityTest(getApplicationContext(),
				new ReachabilityTest.Callback() {

					@Override
					public void onReachabilityTestPassed() {

						try {
							doUi(userClient.getMakeUser(mvMap));
						} catch (Exception e) {
							e.printStackTrace();

						}
					}

					@Override
					public void onReachabilityTestFailed() {
						System.out.println("cec");
					}
				});
	}

	@Pref
	SPreferences_ pref;

	@Trace
	@UiThread
	void doUi(String string) {
		// TODO Auto-generated method stub
		// System.out.println("user " + string);
		ObjectMapper mapper = new ObjectMapper();

		try {
			User user = mapper.readValue(string, User.class);

			if (user.getUser() != null) {
				// System.out.println("user" + user.getUser().getFirstName());
				// System.out.println("id" + user.getUser().getUserId());
				//
				// System.out.println("mobile "
				// +user.getUser().getMobileNumbers());

				webView.clearCache(true);

				CookieSyncManager cookieSyncMngr = CookieSyncManager
						.createInstance(WebViewActivity.this);
				CookieManager cookieManager = CookieManager.getInstance();
				cookieManager.removeAllCookie();
				cookieManager.removeSessionCookie();

				pref.getId().put(user.getUser().getUserId());

				Intent placesListActivity = new Intent(this,
						LoginActivity_.class);
				startActivity(placesListActivity);
			}

		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Toast.makeText(WebViewActivity.this, string,
		// Toast.LENGTH_SHORT).show();
		// finish();
	}

	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			System.out.println("MyWebViewClient " + url);
			Uri uri = Uri.parse(url);

			if (uri.getEncodedPath().equals("/CommonLogin/md_proxy.jsp")) {

				if (!uri.getEncodedQuery().equals("login=true&appid=Q5fyQL")) {
					// doBackground(uri.getEncodedQuery());
					// System.out.println("logded " + url);

					System.out
							.println("getEncodedPath " + uri.getEncodedPath());
					System.out.println("getEncodedFragment "
							+ uri.getEncodedFragment());
					System.out.println("getEncodedFragment "
							+ uri.getEncodedFragment());
					System.out.println("getEncodedQuery "
							+ uri.getEncodedQuery());
					// ############################## CHANGES DONE BY THINKCUBE
					// #######################################

					// webView.goBack();
					webView.loadUrl(url);

					// ############################## CHANGES DONE BY THINKCUBE
					// #######################################
					return true;

				}
				webView.loadUrl(url);
			} else {
				webView.loadUrl(url);
			}
			// webView.loadUrl(url);
			return false;
		}

		// ############################## CHANGES DONE BY THINKCUBE
		// #######################################
		@Override
		public void onPageFinished(WebView view, String url) {

			Uri uri = Uri.parse(url);
			System.out.println("Page has been finished =========== " + url);
			if (uri.getEncodedPath().equals("/login-response")) {
				System.out.println("Final Page has been finished =========== "
						+ url);
				// webView.loadUrl("https://guru.dialog.lk/api/user/login");

				CountDownTimer timer = new CountDownTimer(10000, 1000) {
					public void onTick(long l) {

					}

					@Override
					public void onFinish() {
						finish();
						startActivity(getIntent());
					};
				}.start();
			}
		}
		// ############################## CHANGES DONE BY THINKCUBE
		// #######################################
	}

	public class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult jsResult) {
			final JsResult finalJsResult = jsResult;
			new AlertDialog.Builder(view.getContext())
					.setMessage(message)
					.setPositiveButton(android.R.string.ok,
							new AlertDialog.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finalJsResult.confirm();
								}
							}).setCancelable(false).create().show();
			return true;
		}
	}
}